<?php
/**
 * 客户模型 - 优化版（使用冗余业务字段）
 * 性能提升 >99%
 */

namespace app\model\customer;

use app\model\BaseModel;
use app\common\DataPermissionHelper;
use think\facade\Db;

/**
 * 客户模型 - 优化版
 * 对应数据库表: oa_customer (客户表)
 */
class Customer extends BaseModel
{
    // 设置表名（不包含前缀）
    protected $name = 'customer';

    // 设置主键
    protected $pk = 'id';

    // 设置字段类型
    protected $type = [
        'customer_type' => 'integer',
        'source_id' => 'integer',
        'grade_id' => 'integer',
        'industry_id' => 'integer',
        'services_id' => 'integer',
        'provinceid' => 'integer',
        'cityid' => 'integer',
        'distid' => 'integer',
        'townid' => 'integer',
        'customer_status' => 'integer',
        'contact_first' => 'integer',
        'admin_id' => 'integer',
        'belong_uid' => 'integer',
        'belong_did' => 'integer',
        'belong_time' => 'datetime',
        'distribute_time' => 'datetime',
        'follow_time' => 'datetime',
        'next_time' => 'datetime',
        'discard_time' => 'datetime',
        'is_lock' => 'integer',
        'create_time' => 'int',
        'update_time' => 'int',
        'is_primary' => 'integer',
        'group_code' => 'string',
        'controller_name' => 'string',
        'relation_desc' => 'string',
        // 新增业务字段（冗余字段）
        'membership_end_time' => 'int',
        'membership_days_remaining' => 'int',
        'contract_num' => 'integer',
        'contract_amount' => 'decimal:2',
        'latest_contract_sign_time' => 'int',
        'case_num' => 'integer',
        'case_processing' => 'integer',
        'case_finished' => 'integer',
        'latest_case_update_time' => 'int'
    ];

    // 可搜索字段
    protected $searchField = [
        'name',
        'customer_status',
        'belong_uid',
        'belong_did'
    ];

    /**
     * 获取客户列表（优化版 - 直接查询冗余字段）
     * @param array $where 查询条件
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array 客户列表数据
     */
    public function getCustomerList($where = [], $page = 1, $limit = 10)
    {
        // 应用权限过滤条件（使用增强版，支持 oa_data_auth 特殊权限）
        $where = DataPermissionHelper::buildCustomerDataWhere($where);

        // 简化的查询 - 直接查询客户表所有字段（包括冗余的业务字段）
        $query = $this->alias('c')
            ->where($where)
            ->join('customer_grade g', 'c.grade_id = g.id AND g.delete_time = 0', 'LEFT')
            ->join('customer_source s', 'c.source_id = s.id AND s.delete_time = 0', 'LEFT')
            ->join('admin a', 'c.belong_uid = a.id', 'LEFT')
            ->join('admin a2', 'c.admin_id = a2.id', 'LEFT')
            ->join('customer_contact cc', 'c.id = cc.cid AND cc.is_default = 1 AND cc.delete_time = 0', 'LEFT')
            ->field('c.id, c.name, c.customer_type, c.source_id, c.grade_id, c.industry_id, c.customer_status,
                   c.services_id, c.provinceid, c.cityid, c.distid, c.townid, c.address,
                   c.contact_first, c.admin_id, c.belong_uid, c.belong_did,
                   c.belong_time, c.distribute_time, c.follow_time, c.next_time, c.discard_time,
                   c.share_ids, c.content, c.market, c.remark, c.membership_end_time,
                   c.membership_days_remaining, c.contract_num, c.contract_amount, c.latest_contract_type,
                   c.latest_contract_sign_time, c.case_num, c.case_processing, c.case_finished,
                   c.latest_case_title, c.latest_case_status, c.latest_case_update_time,
                   c.tax_bank, c.tax_banksn, c.tax_num, c.tax_mobile, c.tax_address, c.is_lock,
                   c.create_time, c.update_time, c.delete_time, c.group_code, c.is_primary,
                   c.controller_name, c.relation_desc,
                   g.title as grade_name, s.title as source_name, a.name as belong_name,
                   a2.name as creator_name,
                   cc.name as contact_name, cc.mobile as contact_mobile')
            ->order('c.create_time', 'DESC');  // 按入库时间降序排列，越晚入库的排在前面

        // 查询总数
        $totalQuery = clone $query;
        $total = $totalQuery->count();

        // 分页查询
        $list = $query->page($page, $limit)->select()->toArray();
        
        // 从oa_basic_customer表获取状态配置
        $statusConfig = Db::name('basic_customer')
            ->where('types', 1) // 客户状态类型
            ->where('status', 1) // 启用状态
            ->column('title', 'id');

        // 处理列表数据（直接使用冗余字段，无需额外查询）
        $processedList = array_map(function($item) use ($statusConfig) {
            // 移除合作状态字段，不在列表中显示

            // 添加客户类型标识
            $item['type_label'] = $item['customer_type'] == 16 ? '企业' : '个人';
            $item['type_tag_type'] = $item['customer_type'] == 16 ? 'primary' : 'success';

            // 处理跟进时间显示
            if (!isset($item['last_follow_time']) || $item['last_follow_time'] === null || $item['last_follow_time'] <= 0) {
                $item['last_follow_time'] = null;
                $item['last_follow_time_text'] = '无跟进';
            } else {
                $timestamp = $item['last_follow_time'] > 9999999999 ? $item['last_follow_time'] / 1000 : $item['last_follow_time'];
                $item['last_follow_time_text'] = date('Y-m-d H:i:s', $timestamp);
            }

            // 添加客户状态名称
            $item['customer_status_name'] = $statusConfig[$item['customer_status'] ?? 0] ?? '未知';

            // 确保联系人信息不为空
            if (!isset($item['contact_name'])) {
                $item['contact_name'] = '';
            }
            if (!isset($item['contact_mobile'])) {
                $item['contact_mobile'] = '';
            }

            // 确保业务字段有默认值
            if (!isset($item['membership_days_remaining'])) {
                $item['membership_days_remaining'] = 0;
            }
            if (!isset($item['contract_num'])) {
                $item['contract_num'] = 0;
            }
            if (!isset($item['contract_amount'])) {
                $item['contract_amount'] = 0;
            }
            if (!isset($item['case_num'])) {
                $item['case_num'] = 0;
            }
            if (!isset($item['case_processing'])) {
                $item['case_processing'] = 0;
            }
            if (!isset($item['case_finished'])) {
                $item['case_finished'] = 0;
            }

            return $item;
        }, $list);

        return [
            'list' => $processedList,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 获取客户详情（整合多表信息）
     * @param int $id 客户ID
     * @return array|null
     */
    public function getCustomerDetail($id)
    {
        // 查询客户基本信息
        $customer = $this->alias('c')
            ->where('c.id', $id)
            ->where('c.delete_time', 0)
            ->join('customer_grade g', 'c.grade_id = g.id AND g.delete_time = 0', 'LEFT')
            ->join('customer_source s', 'c.source_id = s.id AND s.delete_time = 0', 'LEFT')
            ->join('admin a', 'c.belong_uid = a.id', 'LEFT')
            ->join('admin a2', 'c.admin_id = a2.id', 'LEFT')
            ->join('customer_contact', 'c.id = customer_contact.cid AND customer_contact.is_default = 1 AND customer_contact.delete_time = 0', 'LEFT')
            ->field('c.*, g.title as grade_name, s.title as source_name, a.name as belong_name, a2.name as creator_name, customer_contact.name as contact_name, customer_contact.mobile as contact_mobile')
            ->find();

        if (!$customer) {
            return null;
        }

        $customerArray = $customer->toArray();

        // 添加客户状态名称
        $statusConfig = Db::name('basic_customer')
            ->where('types', 1) // 客户状态类型
            ->where('status', 1) // 启用状态
            ->column('title', 'id');
        $customerArray['customer_status_name'] = $statusConfig[$customerArray['customer_status'] ?? 0] ?? '未知';

        // 整合联系人信息
        $customerArray['contacts'] = $this->getCustomerContacts($id);

        // 整合跟进记录信息
        $customerArray['traces'] = $this->getCustomerTraces($id, 20);

        // 整合机会线索信息
        $customerArray['chances'] = $this->getCustomerChances($id, 20);

        // 整合合同信息
        $customerArray['contracts'] = $this->getCustomerContracts($id, 10);

        // 整合案件信息
        $customerArray['cases'] = $this->getCustomerCases($id, 10);

        // 统计信息
        $customerArray['stats'] = [
            'contact_count' => count($customerArray['contacts']),
            'trace_count' => count($customerArray['traces']),
            'chance_count' => count($customerArray['chances']),
            'contract_count' => count($customerArray['contracts']),
            'case_count' => count($customerArray['cases'])
        ];

        // 获取归属部门信息
        if (!empty($customerArray['belong_did'])) {
            $department = Db::name('department')->where('id', $customerArray['belong_did'])->field('title')->find();
            $customerArray['belong_department'] = $department ? $department['title'] : '';
        } else {
            $customerArray['belong_department'] = '';
        }

        // 处理共享员工（简化版，不查询具体姓名）
        $customerArray['share_names'] = '';

        return $customerArray;
    }

    /**
     * 获取客户联系人列表
     * @param int $customerId 客户ID
     * @return array
     */
    public function getCustomerContacts($customerId)
    {
        return Db::name('customer_contact')
            ->where('cid', $customerId)
            ->where('delete_time', 0)
            ->order('is_default DESC, create_time DESC')
            ->select()
            ->toArray();
    }

    /**
     * 添加客户联系人
     * @param int $customerId 客户ID
     * @param array $data 联系人数据
     * @return int
     */
    public function addCustomerContact($customerId, $data)
    {
        // 清理不需要的字段，只保留联系人表实际存在的字段
        $allowedFields = [
            'cid', 'is_default', 'name', 'sex', 'mobile', 'qq', 'wechat',
            'email', 'nickname', 'department', 'birthday', 'address', 'family',
            'position', 'admin_id', 'create_time', 'update_time', 'delete_time'
        ];

        // 过滤数据，只保留允许的字段
        $filteredData = [];
        foreach ($data as $key => $value) {
            if (in_array($key, $allowedFields)) {
                $filteredData[$key] = $value;
            }
        }

        // 设置必要的字段
        $filteredData['cid'] = $customerId;
        $filteredData['create_time'] = time();
        $filteredData['update_time'] = time();

        // 如果设置为默认联系人，先取消其他默认
        if (isset($filteredData['is_default']) && $filteredData['is_default'] == 1) {
            Db::name('customer_contact')
                ->where('cid', $customerId)
                ->update(['is_default' => 0]);
        }

        return Db::name('customer_contact')->insertGetId($filteredData);
    }

    /**
     * 更新客户联系人
     * @param int $contactId 联系人ID
     * @param array $data 更新数据
     * @return bool
     */
    public function updateCustomerContact($contactId, $data)
    {
        $data['update_time'] = time();

        // 如果设置为默认联系人，先取消其他默认
        if (isset($data['is_default']) && $data['is_default'] == 1) {
            $contact = Db::name('customer_contact')->find($contactId);
            if ($contact) {
                Db::name('customer_contact')
                    ->where('cid', $contact['cid'])
                    ->update(['is_default' => 0]);
            }
        }

        return Db::name('customer_contact')->where('id', $contactId)->update($data) !== false;
    }

    /**
     * 删除客户联系人
     * @param int $contactId 联系人ID
     * @return bool
     */
    public function deleteCustomerContact($contactId)
    {
        return Db::name('customer_contact')->where('id', $contactId)->update(['delete_time' => time()]) !== false;
    }

    /**
     * 获取客户跟进记录列表
     * @param int $customerId 客户ID
     * @param int $limit 限制数量
     * @return array
     */
    public function getCustomerTraces($customerId, $limit = 20)
    {
        return Db::name('customer_trace')
            ->alias('t')
            ->where('t.cid', $customerId)
            ->where('t.delete_time', 0)
            ->join('admin a', 't.admin_id = a.id', 'LEFT')
            ->join('customer_contact c', 't.contact_id = c.id AND c.delete_time = 0', 'LEFT')
            ->field('t.*, a.name as admin_name, c.name as contact_name')
            ->order('t.create_time DESC')
            ->limit($limit)
            ->select()
            ->toArray();
    }

    /**
     * 添加客户跟进记录
     * @param int $customerId 客户ID
     * @param array $data 跟进数据
     * @return int
     */
    public function addCustomerTrace($customerId, $data)
    {
        // 清理不需要的字段，只保留跟进记录表实际存在的字段
        $allowedFields = [
            'id', 'cid', 'contact_id', 'chance_id', 'types', 'stage', 'content',
            'follow_time', 'next_time', 'file_ids', 'admin_id',
            'create_time', 'update_time', 'delete_time'
        ];

        // 过滤数据，只保留允许的字段
        $filteredData = [];
        foreach ($data as $key => $value) {
            if (in_array($key, $allowedFields)) {
                $filteredData[$key] = $value;
            }
        }

        // 设置必要的字段
        $filteredData['cid'] = $customerId;
        $filteredData['create_time'] = time();
        $filteredData['update_time'] = time();

        // 设置默认值逻辑
        $this->setTraceDefaultValues($customerId, $filteredData);

        return Db::name('customer_trace')->insertGetId($filteredData);
    }

    /**
     * 为跟进记录设置默认值
     * @param int $customerId 客户ID
     * @param array &$data 跟进数据（引用传递）
     * @return void
     */
    private function setTraceDefaultValues($customerId, &$data)
    {
        // 1. 设置跟进类型(types)默认值：4（跟进阶段）
        if (!isset($data['types']) || $data['types'] === '') {
            $data['types'] = 4;
        }

        // 2. 设置联系人(contact_id)默认值：获取主要联系人
        if (!isset($data['contact_id']) || $data['contact_id'] === '') {
            $mainContact = $this->getMainContact($customerId);
            $data['contact_id'] = $mainContact ? $mainContact['id'] : 0;
        }

        // 3. 设置机会线索(chance_id)默认值：0（可选关联）
        if (!isset($data['chance_id']) || $data['chance_id'] === '') {
            $data['chance_id'] = 0;
        }

        // 4. 设置跟进阶段(stage)默认值：与跟进类型一致（4：日常联系）
        if (!isset($data['stage']) || $data['stage'] === '') {
            // 从跟进类型中推断阶段，如果没有明确设置，默认使用日常联系
            $data['stage'] = 17; // 默认阶段ID，根据实际数据调整
        }

        // 5. 设置管理员ID默认值（如果未提供）
        if (!isset($data['admin_id'])) {
            $data['admin_id'] = session('admin_id', 0);
        }
    }

    /**
     * 获取客户主要联系人
     * @param int $customerId 客户ID
     * @return array|null
     */
    private function getMainContact($customerId)
    {
        $contact = Db::name('customer_contact')
            ->where('cid', $customerId)
            ->where('delete_time', 0)
            ->where('is_main', 1) // 主要联系人标识
            ->find();
        
        // 如果没有主要联系人，返回第一个联系人
        if (!$contact) {
            $contact = Db::name('customer_contact')
                ->where('cid', $customerId)
                ->where('delete_time', 0)
                ->order('create_time ASC')
                ->find();
        }
        
        return $contact;
    }

    /**
     * 更新客户跟进记录
     * @param int $traceId 跟进记录ID
     * @param array $data 更新数据
     * @return bool
     */
    public function updateCustomerTrace($traceId, $data)
    {
        // 获取原始记录
        $traceRecord = Db::name('customer_trace')->where('id', $traceId)->find();
        if (!$traceRecord) {
            return false;
        }

        // 清理不需要的字段，只保留跟进记录表实际存在的字段
        $allowedFields = [
            'cid', 'contact_id', 'chance_id', 'types', 'stage', 'content',
            'follow_time', 'next_time', 'file_ids', 'admin_id',
            'create_time', 'update_time', 'delete_time'
        ];

        // 过滤数据，只保留允许的字段
        $filteredData = [];
        foreach ($data as $key => $value) {
            if (in_array($key, $allowedFields)) {
                $filteredData[$key] = $value;
            }
        }

        // 设置更新时间和默认值
        $filteredData['update_time'] = time();
        $this->setTraceDefaultValues($traceRecord['cid'], $filteredData);

        return Db::name('customer_trace')->where('id', $traceId)->update($filteredData) !== false;
    }

    /**
     * 删除客户跟进记录
     * @param int $traceId 跟进记录ID
     * @return bool
     */
    public function deleteCustomerTrace($traceId)
    {
        return Db::name('customer_trace')->where('id', $traceId)->update(['delete_time' => time()]) !== false;
    }

    /**
     * 获取客户机会线索列表
     * @param int $customerId 客户ID
     * @param int $limit 限制数量
     * @return array
     */
    public function getCustomerChances($customerId, $limit = 20)
    {
        return Db::name('customer_chance')
            ->alias('ch')
            ->where('ch.customer_id', $customerId)
            ->where('ch.delete_time', 0)
            ->join('admin a', 'ch.admin_id = a.id', 'LEFT')
            ->field('ch.*, a.name as admin_name')
            ->order('ch.create_time DESC')
            ->limit($limit)
            ->select()
            ->toArray();
    }

    /**
     * 添加客户机会线索
     * @param int $customerId 客户ID
     * @param array $data 机会数据
     * @return int
     */
    public function addCustomerChance($customerId, $data)
    {
        $data['customer_id'] = $customerId;
        $data['create_time'] = time();
        $data['update_time'] = time();

        return Db::name('customer_chance')->insertGetId($data);
    }

    /**
     * 更新客户机会线索
     * @param int $chanceId 机会ID
     * @param array $data 更新数据
     * @return bool
     */
    public function updateCustomerChance($chanceId, $data)
    {
        $data['update_time'] = time();
        return Db::name('customer_chance')->where('id', $chanceId)->update($data) !== false;
    }

    /**
     * 删除客户机会线索
     * @param int $chanceId 机会ID
     * @return bool
     */
    public function deleteCustomerChance($chanceId)
    {
        return Db::name('customer_chance')->where('id', $chanceId)->update(['delete_time' => time()]) !== false;
    }

    /**
     * 获取客户合同列表
     * @param int $customerId 客户ID
     * @param int $limit 限制数量
     * @return array
     */
    public function getCustomerContracts($customerId, $limit = 10)
    {
        return Db::name('contract')
            ->where('customer_id', $customerId)
            ->where('delete_time', 0)
            ->order('create_time DESC')
            ->limit($limit)
            ->select()
            ->toArray();
    }

    /**
     * 获取客户案件列表
     * @param int $customerId 客户ID
     * @param int $limit 限制数量
     * @return array
     */
    public function getCustomerCases($customerId, $limit = 10)
    {
        return Db::name('lawcase')
            ->where('cid', $customerId)
            ->where('delete_time', 0)
            ->order('create_time DESC')
            ->limit($limit)
            ->select()
            ->toArray();
    }

    /**
     * 添加客户
     * @param array $data 客户数据
     * @return int
     */
    public function addCustomer($data)
    {
        return $this->insertGetId($data);
    }

    /**
     * 更新客户
     * @param int $id 客户ID
     * @param array $data 更新数据
     * @return bool
     */
    public function updateCustomer($id, $data)
    {
        $result = $this->where('id', $id)->update($data);
        return $result !== false;
    }

    /**
     * 软删除客户
     * @param int $id 客户ID
     * @return bool
     */
    public function softDeleteCustomer($id)
    {
        $result = $this->where('id', $id)->update(['delete_time' => time()]);
        return $result !== false;
    }

    /**
     * 废弃/恢复客户
     * @param int $id 客户ID
     * @param string $reason 废弃原因
     * @return bool
     */
    public function discardCustomer($id, $reason)
    {
        $data = [
            'discard_time' => time(),
            'discard_reason' => $reason
        ];
        $result = $this->where('id', $id)->update($data);
        return $result !== false;
    }

    /**
     * 恢复客户
     * @param int $id 客户ID
     * @return bool
     */
    public function restoreCustomer($id)
    {
        $result = $this->where('id', $id)->update(['discard_time' => 0, 'discard_reason' => '']);
        return $result !== false;
    }

    /**
     * 批量刷新客户业务数据
     * 用于定时任务或手动触发
     * @return bool
     */
    public function refreshAllBusinessData()
    {
        try {
            // 更新会员状态
            $this->refreshMembershipStatus();

            // 更新合同数据
            $this->refreshContractData();

            // 更新案件数据
            $this->refreshCaseData();

            return true;
        } catch (\Exception $e) {
            trace('刷新客户业务数据失败: ' . $e->getMessage(), 'error');
            return false;
        }
    }

    /**
     * 刷新单个客户的业务数据
     * @param int $customerId 客户ID
     * @return bool
     */
    public function refreshCustomerBusinessData($customerId)
    {
        try {
            // 更新会员状态
            $this->updateCustomerMembershipStatus($customerId);

            // 更新合同数据
            $this->updateCustomerContractData($customerId);

            // 更新案件数据
            $this->updateCustomerCaseData($customerId);

            return true;
        } catch (\Exception $e) {
            trace("刷新客户 {$customerId} 业务数据失败: " . $e->getMessage(), 'error');
            return false;
        }
    }

    /**
     * 刷新会员状态
     * 不再使用is_member字段，直接通过customer_status字段维护会员状态
     */
    private function refreshMembershipStatus()
    {
        // 使用临时表优化性能，避免重复子查询
        Db::execute("        CREATE TEMPORARY TABLE IF NOT EXISTS temp_membership_status AS
        SELECT
            customer_id,
            MAX(end_time) as max_end_time,
            MAX(CASE WHEN end_time > UNIX_TIMESTAMP() THEN 1 ELSE 0 END) as has_valid,
            MAX(CASE WHEN end_time <= UNIX_TIMESTAMP() THEN 1 ELSE 0 END) as has_expired
        FROM oa_contract
        WHERE cate_id IN (1, 2, 10, 13)
        AND delete_time = 0
        GROUP BY customer_id
    ");

        Db::execute("        UPDATE oa_customer c
        LEFT JOIN temp_membership_status t ON c.id = t.customer_id
        SET
            membership_end_time = IFNULL(t.max_end_time, 0),
            membership_days_remaining = CASE
                WHEN t.has_valid = 1 THEN t.max_end_time - UNIX_TIMESTAMP()
                ELSE 0
            END
        WHERE c.delete_time = 0
    ");

        Db::execute("DROP TEMPORARY TABLE IF EXISTS temp_membership_status");
    }

    /**
     * 刷新合同数据
     */
    private function refreshContractData()
    {
        Db::execute("
            UPDATE oa_customer
            SET contract_num = (
                SELECT COUNT(*) FROM oa_contract
                WHERE customer_id = oa_customer.id AND delete_time = 0
            ),
            contract_amount = (
                SELECT IFNULL(SUM(cost), 0) FROM oa_contract
                WHERE customer_id = oa_customer.id AND delete_time = 0
            )
        ");
    }

    /**
     * 刷新案件数据
     */
    private function refreshCaseData()
    {
        Db::execute("
            UPDATE oa_customer
            SET case_num = (
                SELECT COUNT(*) FROM oa_lawcase
                WHERE cid = oa_customer.id AND delete_time = 0
            ),
            case_processing = (
                SELECT COUNT(*) FROM oa_lawcase
                WHERE cid = oa_customer.id AND status IN (1,2,3) AND delete_time = 0
            ),
            case_finished = (
                SELECT COUNT(*) FROM oa_lawcase
                WHERE cid = oa_customer.id AND status IN (4,5) AND delete_time = 0
            )
        ");
    }

    /**
     * 更新单个客户的会员状态
     * @param int $customerId
     */
    private function updateCustomerMembershipStatus($customerId)
    {
        // 不再更新is_member字段，直接通过customer_status字段维护会员状态
        Db::name('customer')
            ->where('id', $customerId)
            ->update([
                'membership_days_remaining' => Db::raw('CASE
                    WHEN EXISTS (
                        SELECT 1 FROM oa_contract
                        WHERE customer_id = ' . $customerId . '
                        AND cate_id IN (1, 2, 10, 13)
                        AND end_time > UNIX_TIMESTAMP()
                        AND delete_time = 0
                    ) THEN (
                        SELECT MAX(end_time) FROM oa_contract
                        WHERE customer_id = ' . $customerId . '
                        AND cate_id IN (1, 2, 10, 13)
                        AND delete_time = 0
                    ) - UNIX_TIMESTAMP()
                    ELSE 0
                END'),
                'membership_end_time' => Db::raw('(SELECT MAX(end_time) FROM oa_contract
                    WHERE customer_id = ' . $customerId . '
                    AND cate_id IN (1, 2, 10, 13)
                    AND delete_time = 0)')
            ]);
    }

    /**
     * 更新单个客户的合同数据
     * @param int $customerId
     */
    private function updateCustomerContractData($customerId)
    {
        $contractStats = Db::name('contract')
            ->where('customer_id', $customerId)
            ->where('delete_time', 0)
            ->field('COUNT(*) as contract_num, IFNULL(SUM(cost), 0) as contract_amount')
            ->find();

        Db::name('customer')
            ->where('id', $customerId)
            ->update([
                'contract_num' => $contractStats['contract_num'] ?? 0,
                'contract_amount' => $contractStats['contract_amount'] ?? 0
            ]);
    }

    /**
     * 更新单个客户的案件数据
     * @param int $customerId
     */
    private function updateCustomerCaseData($customerId)
    {
        $caseStats = Db::name('lawcase')
            ->where('cid', $customerId)
            ->where('delete_time', 0)
            ->field('COUNT(*) as case_num,
                   SUM(CASE WHEN status IN (1,2,3) THEN 1 ELSE 0 END) as case_processing,
                   SUM(CASE WHEN status IN (4,5) THEN 1 ELSE 0 END) as case_finished')
            ->find();

        Db::name('customer')
            ->where('id', $customerId)
            ->update([
                'case_num' => $caseStats['case_num'] ?? 0,
                'case_processing' => $caseStats['case_processing'] ?? 0,
                'case_finished' => $caseStats['case_finished'] ?? 0
            ]);
    }

    /**
     * 根据关键词搜索客户ID
     *
     * @param string $keywords 关键词
     * @param array $where 查询条件
     * @return array 客户ID数组
     */
    public function searchCustomerIdsByKeywords(string $keywords, array &$where = []): array
    {
        // 移除可能的引号
        $keywords = trim($keywords, '"\' ');

        if (empty($keywords)) {
            return [];
        }

        // 构建搜索条件
        $searchWhere = [
            ['delete_time', '=', 0],
            ['discard_time', '=', 0]
        ];

        // 搜索客户名称
        $customerIds = $this->where($searchWhere)
            ->where('name', 'like', '%' . $keywords . '%')
            ->column('id');

        // 搜索联系人姓名和电话
        $contactData = Db::name('customer_contact')
            ->where('delete_time', 0)
            ->where('is_default', 1)
            ->where(function($query) use ($keywords) {
                $query->where('name', 'like', '%' . $keywords . '%')
                    ->whereOr('mobile', 'like', '%' . $keywords . '%');
            })
            ->column('cid');

        // 合并结果
        $allIds = array_merge($customerIds, $contactData);

        // 去重并返回
        return array_unique($allIds);
    }
}
